<script>
    let flatArr=[
        {
            "id": 1,
            "name": "北京",
            "parentId": 0
        },
        {
            "id": 4,
            "name": "南京",
            "parentId": 2
        },
        {
            "id": 5,
            "name": "徐州",
            "parentId": 2
        },
        {
            "id": 6,
            "name": "扬州",
            "parentId": 2
        },
        {
            "id": 2,
            "name": "江苏",
            "parentId": 0
        },
        {
            "id": 9,
            "name": "汊河",
            "parentId": 7
        },
        {
            "id": 7,
            "name": "滁州",
            "parentId": 3
        },
        {
            "id": 8,
            "name": "合肥",
            "parentId": 2
        },
        {
            "id": 3,
            "name": "安徽",
            "parentId": 0
        }
    ]
    //currentKey当前节点的字段标识（属性名）
    //parentKey父节点的字段标识（属性名）
    //childKey子节点的字段标识（属性名）
    function toTree(data,currentKey="id",parentKey="parentId",childKey="children"){
        //储存树形数据的数组
        let treeArr=[]
        //再次声明一个函数
        function recursion(data){
            data.forEach(item => {
                if(item[parentKey]){
                    let parent=data.find(p=>p[currentKey]===item[parentKey])
                    if(!parent[childKey]){
                        parent[childKey]=[]
                    }
                    parent[childKey].push(item)
                }else{
                    treeArr.push(item)
                }
            });
        }
        recursion(data)
        return treeArr
    }
    
   let tree=toTree(flatArr,"id","parentId")
    console.log(tree)
</script>